﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class UIInputCounter : MonoBehaviour
{
    [SerializeField] private int _counter = 0;

    [System.Serializable]
    public class CounterUpdateEvent : UnityEvent<int> { };

    public int counter
    {
        get { return _counter; }
        set
        {
            if (_counter != value)
            {
                _counter = value;
                this.UpdateCounter();
                onCounterChange?.Invoke(value);
            }
        }
    }


    public int min = 0;
    public int max = 9999;

    public InputField numberField;
    public Button buttonLeft;
    public Button buttonRight;

    //标签切换回调函数，标签切换时使用，控制一个
    public CounterUpdateEvent onCounterChange;

    private void Awake()
    {
        buttonLeft.onClick.AddListener(SubCount);
        buttonRight.onClick.AddListener(AddCount);
        numberField.onEndEdit.AddListener(OnEditCounter);
        numberField.text = counter.ToString();
        this.UpdateCounter();
    }

    public void OnEditCounter(string str)
    {
        int value = 0;
        int.TryParse(str, out value);
        this.counter = Mathf.Clamp(value, min, max);
    }

    public void AddCount()
    {
        this.counter = Mathf.Clamp(this.counter + 1, min, max);
    }

    public void SubCount()
    {
        this.counter = Mathf.Clamp(this.counter - 1, min, max);
    }

    public void UpdateCounter()
    {
        this.numberField.text = _counter.ToString();
    }

}
